#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <functional>
#include <sys/stat.h>
#include <vector>
#include <fcntl.h>
#include<pthread.h>
#include <sys/wait.h>
#include "Handler.hpp"
#include<unordered_map>
using namespace std;





class sever
{
public:
    sever(uint16_t port)
        : _listensock(-1), _port(port)
    {
    }
#define defaultip "0.0.0.0"
    void init()
    {
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock == -1)
        {
            cerr <<"socket error"<<endl;
            exit(SOCKET_ERR);
        }
        else
           cout<<"socket create success"<<endl;

        // 绑定端口号和ip
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(_port);
        string ip = defaultip;
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        socklen_t len = sizeof addr;
        int n = bind(_listensock, (struct sockaddr *)&addr, len);
        if (n == -1)
        {
            cerr<<"bind error"<<endl;
            exit(BIND_ERR);
        }
        else
            cout<<"bind success"<<endl;
#define defaultbacklog 5
        n = listen(_listensock, defaultbacklog);
        if (n == -1)
        {
            cerr<<"listen err"<<endl;
            exit(LISTEN_ERR);
        }
        else
        cout<<"listen success"<<endl;
    }

    void start()
    {
        // 死循环从监听套接字中获取新连接
        initContentType();
        while (true)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof client;
            int sock = accept(_listensock, (struct sockaddr *)&client, &len);
            if (sock == -1)
            {
                cerr<<"accept error"<<endl;
                exit(ACCEPT_ERR);
            }
            else
                cout << "accept a new link , sock :" << sock << endl;
           
            uint16_t clientport = ntohs(client.sin_port);
            string clientip = inet_ntoa(client.sin_addr);
            if(fork()==0) //子进程
            {
                if(fork()>0) exit(0);
                Handler(sock,clientport,clientip); //服务端逻辑
            }
            wait(nullptr);
        }
    }

private:
    int _listensock;
    uint16_t _port;
};
